package com.cnswhy.cloud.server.core.utils.BaiduAip;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.util.Base64Util;
import com.cnswhy.cloud.server.core.entity.BankCardResult;
import lombok.extern.slf4j.Slf4j;

import java.net.URLEncoder;

/**
 * ClaseName：Bankcard
 * Description：
 * Author：JensenWei
 * QQ: 2188307188
 * Createtime：2018/3/10 11:04
 * Modified By：
 * Fixtime：2018/3/10 11:04
 * FixDescription：
 */
@Slf4j
public class Bankcard {

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static void main(String[] args) {
        // 银行卡识别url
        String bankcardIdentificate = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard";
        // 本地图片路径
        String filePath = "http://121.201.20.215/group1/M00/03/FE/wKhkclqmJpCAYy9JAAI-G3Dj5jQ768.jpg";
        try {
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String params = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(imgStr, "UTF-8");
            /**
             * 线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
             */
            String accessToken = AuthService.getAuth();
            String result = HttpUtil.post(bankcardIdentificate, accessToken, params);
            BankCardResult bankCardResult = new BankCardResult();
            bankCardResult = JSON.parseObject(result, BankCardResult.class);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static BankCardResult identify(String path) {
        // 银行卡识别url
        String bankcardIdentificate = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard";
        // 本地图片路径
        String filePath = path;
        try {
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String params = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(imgStr, "UTF-8");
            /**
             * 线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
             */
            String accessToken = AuthService.getAuth();
            String result = HttpUtil.post(bankcardIdentificate, accessToken, params);
            BankCardResult bankCardResult = new BankCardResult();
            bankCardResult = JSON.parseObject(result, BankCardResult.class);
            log.info(result);
            return bankCardResult;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}